import { defineStore } from "pinia"
import { onMounted, ref } from "vue"
import { get, post } from "@/utils/api"
import { MessagePlugin } from "tdesign-vue-next"

export const useAdminPayStore = defineStore("adminPay", () => {
  const common = {
    showType: ref("1"),
    saveConfig: async () => {
      try {
        // 保存微信支付配置
        const wechatPayResponse = await post("/api/wechatPay/saveConfig", wechatPay.formData.value)
        // 保存支付宝支付配置
        const aliPayResponse = await post("/api/aliPay/saveConfig", aliPay.formData.value)
        if(wechatPayResponse.status === "success" && aliPayResponse.status === "success"){
          await MessagePlugin("success", "配置保存成功！")
        }else {
          await MessagePlugin("error", "配置保存失败！")
        }
        await wechatPay.getConfig()
        await aliPay.getConfig()
      } catch (err) {
        console.log(err)
      }
    }
  }
  const wechatPay = {
    formData: ref({
      id: 1,
      mchid: "",
      appid: "",
      api_key_v3: "",
      serial_number: "",
      private_key: "",
      status: 0
    }),
    getConfig: async () => {
      try {
        wechatPay.formData.value = await get("/api/wechatPay/getConfig")
      } catch (err) {
        console.log(err)
      }
    }
  }
  const aliPay = {
    formData: ref({
      id: 1,
      appid: "",
      public_key: "",
      private_key: "",
      status: 0
    }),
    getConfig: async () =>{
      try {
        aliPay.formData.value = await get("/api/aliPay/getConfig")
      } catch (err) {
        console.log(err)
      }
    }
  }

  onMounted(async () => {
    await wechatPay.getConfig()
    await aliPay.getConfig()
  })

  return {
    wechatPay,
    aliPay,
    common
  }
})
